<?php
	
	if( !isset($_COOKIE["username"]) ){
		header("Location:login.php");
	}else{
		setcookie("username", $_COOKIE["username"],time() + 900);
	}

	
	include_once 'json_function.php';
	
	$ini_array = parse_ini_file("config/config.ini");
	
	$conn = @mysqli_connect($ini_array["host"], $ini_array["username"], $ini_array["password"], $ini_array["db_name"]) or die("cann't connect the mysql db");
	mysqli_set_charset($conn, "utf8");
	ini_set('default_charset', "UTF-8");
	$No = mysqli_real_escape_string($conn,$_POST["No"]);
	$type = mysqli_real_escape_string($conn,$_POST["type"]);

	//type=1:table=patient
	//type=2:table=doctor
	//type=3:table=appointment
	//type=4:table=visit
	//type=5:table=procedure
	if( $type == 1 ){
		$deleteSql = "delete from patient where patient_no=".$No;
		$result = mysqli_query($conn, $deleteSql);
		$data = "{\"data\":{";
		if( $result ){
			$data .= "\"status\":\"success\",\"No\":\"".$No."\"";
		}else{
			$data .= "\"status\":\"fail\",\"msg\":\"".mysqli_error($conn)."\"";
		}
		$data .= "}}";
		echo JsonCharFilter($data);
	}else if($type == 2 ){
		$deleteSql = "delete from doctor where doctor_no=".$No;
		$result = mysqli_query($conn, $deleteSql);
		$data = "{\"data\":{";
		if( $result ){
			$data .= "\"status\":\"success\",\"No\":\"".$No."\"";
		}else{
			$data .= "\"status\":\"fail\",\"msg\":\"".mysqli_error($conn)."\"";
		}
		$data .= "}}";
		echo JsonCharFilter($data);
	}else if( $type == 3 ){
		$deleteSql = "delete from appointment where appointment_no=".$No;
		$result = mysqli_query($conn, $deleteSql);
		$data = "{\"data\":{";
		if( $result ){
			$data .= "\"status\":\"success\",\"No\":\"".$No."\"";
		}else{
			$data .= "\"status\":\"fail\",\"msg\":\"".mysqli_error($conn)."\"";
		}
		$data .= "}}";
		echo JsonCharFilter($data);
	}else if ( $type == 4){
		mysqli_query($conn, "BEGIN");
		$deleteSql = "delete from visit where appointment_no=".$No;
		$updateSql = "update appointment set type=2 where appointment_no=".$No;
		$result = mysqli_query($conn, $deleteSql);
		$data = "{\"data\":{";
		if( $result ){
			$result = mysqli_query($conn, $updateSql);
			if( $result ){
				mysqli_query($conn, "COMMIT");
				$data .= "\"status\":\"success\",\"No\":\"".$No."\"";
			}else{
				mysqli_query("ROLLBACK");
				$data .= "\"status\":\"fail\",\"msg\":\"".mysqli_error($conn)."\"";
			}
		}else{
			$data .= "\"status\":\"fail\",\"msg\":\"".mysqli_error($conn)."\"";
		}
		$data .= "}}";
		echo JsonCharFilter($data);
	}else if( $type == 5 ){
		$deleteSql = "delete from procedurelist where procedure_no=".$No;
		$result = mysqli_query($conn, $deleteSql);
		$data = "{\"data\":{";
		if( $result ){
			$data .= "\"status\":\"success\",\"No\":\"".$No."\"";
		}else{
			$data .= "\"status\":\"fail\",\"msg\":\"".mysqli_error($conn)."\"";
		}
		$data .= "}}";
		echo JsonCharFilter($data);
	}
	mysqli_close($conn);
?>